package logic
{
	import adobe.utils.CustomActions;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;
	import gc.states;
	
	import structures.Structure;
	import gc.events;
	
	public class UnitFactory extends MovieClip
	{
		private var stageRef:DisplayObjectContainer;
		private var list:Vector.<Class>
		private var buildingStruct:Structure;
		
		public function UnitFactory() 
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
			
		}
		
		public function init(e:Event):void
		{
			stageRef = parent;
			list = new Vector.<Class>();
		
			//add listeners
			{
				stageRef.addEventListener(events.START_BUILD, startbuild_handler);
				//stageRef.addEventListener(events.COMPLETE_BUILD, completebuild_handler);
				stageRef.addEventListener(events.BUILDING_PLACED, buildingplace_handler);
			}
		}
		
		public function push(c:Class):void
		{
			if (c.prototype instanceof Structure)
			{
				list.push(c);
				return;
			}
		}
		
		public function getClassFromIndex(index:int):Class
		{
			var structClass:Class;
			
			try
			{
				structClass = list[index];
			}
			catch (err:Error)
			{
				trace(err);
				structClass = null;
			}
			
			return structClass;
		}
		
		public function checkIndex(index:int):Boolean
		{
			return (index != states.None && index < list.length);
		}
		
		public function beginBuild(index:int):Boolean
		{
		
			try 
			{
				if (checkIndex(index))
				{
					//build here
					var structClass:Class = getClassFromIndex(index);
					buildingStruct = new structClass();
					buildingStruct.activate();
					
					//pass reference to new struct thru event? probably
					dispatchEvent(new CustomEvent(events.NOW_BUILDING, buildingStruct));
					
					return true;
				}
			}
			catch (err:Error)
			{
				trace(err);
				
			}
			
			return false;
		}
		
		private function isValid():Boolean
		{
			//fill in later
			return true;
		}
		
		private function buildingplace_handler(e:CustomEvent):void
		{
			try 
			{
				var x:Number = e.getArgs()[0];
				var y:Number = e.getArgs()[1];
				
				if (isValid())
				{
					completeBuild();
				}
			}
			catch (err:Error)
			{
				trace(err);
			}
		}
		
		private function completeBuild():void
		{
			buildingStruct.deactivate();
			dispatchEvent(new CustomEvent(events.COMPLETE_BUILD, buildingStruct));
			dispatchEvent(new CustomEvent(events.SET_FREE));
			clearBuilding();
		}
		
		private function clearBuilding():void
		{
			buildingStruct = null;
		}
		
		private function startbuild_handler(e:CustomEvent):void
		{
			
			var isWorking:Boolean = beginBuild(e.getArgs());
		}
		
	}

}